import jwt, { JwtPayload } from 'jsonwebtoken'
import { NextFunction, Request, Response } from 'express'
import { Unauthorized } from 'http-errors'
import { failure } from '@/utils/response'
import { redisClient } from '@/utils/redis'

const userAuth = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '')
    if (!token) {
      throw new Unauthorized('当前接口需要认证才能访问')
    }
    const decoded = jwt.verify(token, process.env.SECRET as string) as JwtPayload
    const { userId, exp } = decoded
    const client = await redisClient()
    const tk = await client.get(`token:${userId}:${token}`)
    if (tk) {
      throw new Unauthorized('token已过期')
    }
    req.userId = userId
    req.expiresTimestamp = exp
    next()
  } catch (error) {
    failure(res, error as Error)
  }
}

export default userAuth
